//
//  UIViewController+ACExt.m
//  ACFramework
//
//  Created by caoyq on 2018/5/23.
//

#import "UIViewController+ACExt.h"

@implementation UIViewController (ACExt)

#pragma mark - Push + Pop

- (BOOL)ac_isPush
{
    NSArray *viewControllers = self.navigationController.viewControllers;
    if (viewControllers.count > 1 && [viewControllers objectAtIndex:viewControllers.count-2] == self) {
        //当前视图控制器在栈中，故为push操作
        return YES;
    } else if ([viewControllers indexOfObject:self] == NSNotFound) {
        //当前视图控制器不在栈中，故为pop操作
    }
    return NO;
}

- (void)ac_presentViewController: (UIViewController *)vc
{
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)ac_pushViewController: (UIViewController *)vc
{
    if (!vc) {
        return;
    }
    if ([self isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)self;
        [nav pushViewController:vc animated:YES];
    }else {
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)ac_popViewController
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)ac_popToViewControllerAtIndex: (NSInteger)index
{
    //截止到当前VC，控制器的个数
    NSInteger vcCount = [self.navigationController.viewControllers indexOfObject:self];
    [self.navigationController popToViewController:self.navigationController.viewControllers[vcCount - index] animated:YES];
}

#pragma mark - 获取控制器

- (UIViewController *)ac_viewControllersAtIndex: (NSInteger)index
{
    NSInteger vcCount = [self.navigationController.viewControllers indexOfObject:self];
    return self.navigationController.viewControllers[vcCount - index];
}

- (UIViewController *)ac_topViewController {
    UIViewController *topVc = [UIApplication sharedApplication].keyWindow.rootViewController;
    if ([topVc isKindOfClass:[UITabBarController class]]) {
        topVc = ((UITabBarController *)topVc).selectedViewController;
    }
    NSArray *vcs = nil;
    if ([topVc isKindOfClass:[UINavigationController class]]) {
        vcs = ((UINavigationController *)topVc).viewControllers;
    }else {
        vcs = topVc.navigationController.viewControllers;
    }
    return vcs ? vcs.lastObject : nil;
}

@end
